package client.comm.baoding.fragment

import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.ViewCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import androidx.viewpager.widget.ViewPager
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.utils.Util
import client.comm.octfdsmall.widget.MyScrollview1
import client.comm.baoding.R
import client.comm.baoding.adapter.page.CateGoodsPageAdapter
import client.comm.baoding.adapter.NewSyAdapter
import client.comm.baoding.adapter.SyPagingHeaderAdapter
import client.comm.baoding.api.bean.CateGoods
import client.comm.baoding.api.bean.GoodsIndex
import client.comm.baoding.ui.SearchActivity
import client.comm.baoding.ui.vm.MainViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import android.util.TypedValue
import android.view.ViewGroup
import android.widget.*
import androidx.core.view.children
import client.comm.baoding.databinding.FragmentTaboneBinding
import client.comm.baoding.databinding.FragmentTabwhiteBinding
import client.comm.baoding.databinding.LayoutCatetabItemBinding
import client.comm.commlib.dipToPx
import client.comm.baoding.receiver.MeBroadcast
import client.comm.baoding.ui.NoticeActivity


class TabWhiteFragment : BaseFragment<FragmentTabwhiteBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_tabwhite
    }

    val adapter: NewSyAdapter by lazy {
        NewSyAdapter(requireContext(), mImgLoader).apply {

            //注释时间2.20
//            refreshLoading = {
//                if (itemCount == 0) {
//                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
//                }
//            }

            refreshNotLoading = {
                binding.refreshLayout.isRefreshing = false
            }

//            refreshNotLoading = {
//                binding.refreshLayout.isRefreshing = false
//                if (itemCount == 0) {
//                    binding.emptyLayout.errorType = EmptyLayout.NODATA
//                } else {
//                    binding.emptyLayout.visibility = View.GONE
//                }
//            }
//            refreshError = {
//                if (itemCount == 0)
//                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
//                toast((it).error.message)
//            }


            /*addLoadStateListener {
                when (it.refresh) {
                    is LoadState.NotLoading -> {
//                        binding.refreshLayout.isRefreshing = false
                        if (itemCount == 0) {
                            binding.emptyLayout.errorType = EmptyLayout.NODATA
                        } else {
                            binding.emptyLayout.visibility = View.GONE
                        }
                    }
                    is LoadState.Loading -> {
                        if (itemCount == 0) {
                            binding.emptyLayout.errorType = EmptyLayout.NETWORK_LOADING
                        }
                    }
                    is LoadState.Error -> {
                        if (itemCount == 0)
                            binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                        toast((it.refresh as LoadState.Error).error.message)
                    }
                }
            }*/
        }
    }

    val headerAdapter by lazy {
        SyPagingHeaderAdapter(mImgLoader, requireContext()).apply {
            /*labelClick = {
                it?.let {
                    viewModel.cateId.value = "${it.category_id}"
                    requireActivity().sendBroadcast(Intent(MeBroadcast.MAIN_SWITCH_TAB).apply {
                        putExtra("tabIndex", 1)
                    })
                }
            }*/

            //通知跳转
            notice = {
                startActivity(Intent(requireContext(), NoticeActivity::class.java).apply {
                    putParcelableArrayListExtra("articleList", it)
                })
            }

            changeCheckTab = {
                selectedTab(it)
            }

            changeMainTab = {

                //跳购物车
                requireActivity().sendBroadcast(Intent(MeBroadcast.MAIN_SWITCH_TAB).apply {
                    putExtra("tabIndex", 2)
                })
            }

        }
    }

//    var changeCheckTab: ((position: Int) -> Unit)? = null

    lateinit var pageAdapter: CateGoodsPageAdapter

    override fun initViewModel(): MainViewModel = createViewModel()

    override fun initWidget() {
        binding.event = this
        binding.recyclerView.adapter = adapter.withLoadStateHeader(
//            footer = PagerFooterAdapter(),
            header = headerAdapter
        )
        binding.emptyLayout.setOnClickListener {
            adapter.refresh()
            //getCateData()

        }

        binding.refreshLayout.setOnRefreshListener {
            adapter.refresh()
            //getCateData()
//
        }

//        lifecycleScope.launch {
//            viewModel.pagingDataUser().collect {
//                adapter.submitData(it)
//            }
//        }
        val gridLayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        binding.recyclerView.layoutManager = gridLayoutManager
//        binding.recyclerView.addItemDecoration(
//            SpacePblGridItemDecoration(
//                dipToPx(resources, 15.0f).toInt(),
//                true,
//                binding.recyclerView
//            )
//        )
        viewModel.homeCall.observe(this, Observer {
            it?.let {
                if (it.isSuccess) {
                    headerAdapter.goodsIndex = it.data!!

//                    val list = it.data!!.tj_goods_list as MutableList<GoodsIndex.TjGoods?>
//                    if (list.size > 0) {
//                        binding.emptyLayout.visibility = View.GONE
//                    }
                } else {
//                    if (adapter.itemCount == 0) {
//                        binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
//                    }

                }
            }

        })

        initCate()
    }


    var isFloat: Boolean = false //是否处于悬浮状态

    private fun initCate() {
        binding.myScrollView.setScrollViewListener(object : MyScrollview1.ScrollViewListener {
            override fun onScrollChanged(
                scrollView: MyScrollview1?,
                l: Int,
                t: Int,
                oldl: Int,
                oldt: Int
            ) {
                val recyclerView = binding.recyclerView
                val layout = binding.svLayoutTab
                val mTabLayout = binding.tabContent

                val mlLayout2 = binding.svLayoutTab1

                if (t > recyclerView.height && mTabLayout.parent === layout) {
                    layout.removeView(mTabLayout)
                    mlLayout2.addView(mTabLayout)//
                    mlLayout2.setBackgroundColor(resources!!.getColor(R.color.main_bg))

                    var parentLayout = RelativeLayout(requireContext())
                    setLayoutTabMargin(mlLayout2, parentLayout!!, -10f)
                    isFloat = true

                } else if (t < recyclerView.height && mTabLayout.parent === mlLayout2) {
                    mlLayout2.removeView(mTabLayout)//
                    layout.addView(mTabLayout)
                    layout.setBackgroundColor(Color.TRANSPARENT)

                    var parentLayout = LinearLayout(requireContext())
                    setLayoutTabMargin(layout, parentLayout!!, 1f)
                    isFloat = false
                }


//                viewModel.cutTab.observe(this@TabOneFragment, Observer {
//                    for ((i, v) in binding.tabContent.children.withIndex()) {
//                        var linearLayout: LinearLayout =
//                            ((binding.tabContent.getChildAt(i)) as LinearLayout)
//                        var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout
//
//                        var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
//                        var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
//                        var vIndicator = linearLayoutSub.getChildAt(2) as ImageView
//
//                        if ("$i".equals(it)) {
//                            v.isSelected = true
//                            onTabSelected(txtTv, txtTvDesc, vIndicator)
//                        } else {
//                            v.isSelected = false
//                            onTabUnselected(txtTv, txtTvDesc, vIndicator)
//                        }
////                        onIndicatorState(txtTv, vIndicator, v.isSelected, isFloat)
//
//                    }
//                })

                //t 滚动的高度
                //解决 SwipeRefreshLayout 与 ScrollView 滑动冲突
                if (t <= 0)
                    binding.refreshLayout.isEnabled = true;
                else
                    binding.refreshLayout.isEnabled = false;

            }

        })


        binding.viewPager.clearOnPageChangeListeners()
        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                selectedTab(position)
//                binding.myScrollView.scrollTo(0, 0);

            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

//        getCateData()
    }

    private fun selectedTab(position: Int) {
        viewModel.cutTab.value = "$position"
        binding.viewPager.resetHeight(position)
    }

    private fun setLayoutTabMargin(layout: HorizontalScrollView, vg: ViewGroup, dpf: Float) {
        val margin = ViewGroup.MarginLayoutParams(layout.layoutParams).apply {
            topMargin = dipToPx(layout.resources, dpf).toInt()
        }
        if (vg is LinearLayout) {
            layout.layoutParams = LinearLayout.LayoutParams(margin)
        } else if (vg is RelativeLayout) {
            layout.layoutParams = RelativeLayout.LayoutParams(margin)
        }
    }

//    private fun onIndicatorState(
//        tv: TextView,
//        vIndicator: View,
//        selected: Boolean,
//        isFloat: Boolean
//    ) {
//        if (selected) {//选中
//            if (isFloat) {//悬浮
//                vIndicator.setBackgroundColor(Color.WHITE)
//            } else {
//                vIndicator.setBackgroundColor(resources!!.getColor(R.color.main_color))
//            }
//            tv.setTextColor(resources!!.getColor(R.color.txt_color))
//
//        } else {
//            if (isFloat) {
//                tv.setTextColor(Color.WHITE)
//            } else {
//                tv.setTextColor(resources!!.getColor(R.color.hint_color))
//            }
//            vIndicator.setBackgroundColor(Color.TRANSPARENT)
//        }
//
//    }

    //得到分类数据
    private fun getCateData() {
        viewModel.callCate.observe(this, Observer {
            it?.let {
                if (it.isSuccess && it.data != null) {
                    val list: MutableList<CateGoods.TypeInfo>? =
                        it.data?.category_list as MutableList<CateGoods.TypeInfo>?
                    if (list != null && list.size > 0) {
                        pageAdapter =
                            CateGoodsPageAdapter(childFragmentManager, binding.viewPager, list)
                        binding.tabContent.removeAllViews()
                        for ((i, a) in list.withIndex()) {
                            val tabBinding = DataBindingUtil.inflate<LayoutCatetabItemBinding>(
                                LayoutInflater.from(requireContext()),
                                R.layout.layout_catetab_item,
                                binding.tabContent,
                                false
                            ).apply {
                                index = "${i}"
                                txtTv.text = a.name
                                tvDesc.text = a.name_info
//                                this.root.setOnClickListener {
//                                    binding.viewPager.setCurrentItem(this.index!!.toInt(), false)
//                                    /*it.isSelected = true
//                                    for (v in binding.tabContent.children) {
//                                        if (v != it) {
//                                            v.isSelected = false
//                                        }
//                                    }*/
//                                }
                                onTabUnselected(txtTv, tvDesc, vIndicator)//默认不选中
                                //隐藏竖条分割线
                                if ((list.size - 1) == i) {
                                    vVerticalLine.visibility = View.GONE
                                } else {
                                    vVerticalLine.visibility = View.VISIBLE
                                }

                            }

                            tabBinding.root.setOnClickListener {
                                binding.viewPager.setCurrentItem(tabBinding.index!!.toInt(), false)
                                /*it.isSelected = true
                                for (v in binding.tabContent.children) {
                                    if (v != it) {
                                        v.isSelected = false
                                    }
                                }*/
                            }


                            binding.tabContent.addView(tabBinding.root)

                        }
                        binding.viewPager.adapter = pageAdapter
                        var index = viewModel.cutTab.value!!.toInt()
                        if (!viewModel.cateId.value.isNullOrEmpty()) {
                            for ((i, v) in pageAdapter.list.withIndex()) {
                                if (v.category_id.equals(viewModel.cateId.value)) {
                                    index = i
                                    viewModel.cateId.value = ""
                                    break
                                }
                            }
                        }
                        binding.viewPager.postDelayed({
                            binding.viewPager.setCurrentItem(index, false)

                            var linearLayout: LinearLayout =
                                ((binding.tabContent.getChildAt(index)) as LinearLayout)
                            var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout

                            var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
                            var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
                            var vIndicator = linearLayoutSub.getChildAt(2) as ImageView

                            txtTv.isSelected = true
                            onTabSelected(txtTv, txtTvDesc, vIndicator)//默认选中
                        }, 0)//20


//                        binding.emptyLayout.visibility = View.GONE
                    } else {
//                        binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                    }
                } else {
//                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
            }
        })
        viewModel.cutTab.observe(this, Observer {
            if (!"${binding.viewPager.currentItem}".equals(it)) {
                binding.viewPager.setCurrentItem(it.toInt(), false)
            }

            for ((i, v) in binding.tabContent.children.withIndex()) {

                var linearLayout: LinearLayout =
                    ((binding.tabContent.getChildAt(i)) as LinearLayout)
                var linearLayoutSub = linearLayout.getChildAt(0) as LinearLayout

                var txtTv: TextView = linearLayoutSub.getChildAt(0) as TextView
                var txtTvDesc: TextView = linearLayoutSub.getChildAt(1) as TextView
                var vIndicator = linearLayoutSub.getChildAt(2) as ImageView

                if ("$i".equals(it)) {
                    v.isSelected = true
                    onTabSelected(txtTv, txtTvDesc, vIndicator)
                } else {
                    v.isSelected = false
                    onTabUnselected(txtTv, txtTvDesc, vIndicator)
                }
//                        onIndicatorState(txtTv, vIndicator, v.isSelected, isFloat)
            }

        })
        if (!::pageAdapter.isInitialized && viewModel.callCate.value == null) {
            viewModel.holdCate()
        }

    }


    private fun onTabSelected(textView: TextView, tvDesc: TextView, vIndicator: View) {//
        val selectedSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX,
            30f,
            resources.displayMetrics
        )
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
        textView.setTextColor(resources!!.getColor(R.color.main_color))
        tvDesc.setTextColor(resources!!.getColor(R.color.main_color))
        vIndicator.visibility = View.VISIBLE

    }

    private fun onTabUnselected(textView: TextView, tvDesc: TextView, vIndicator: View) {//
        val selectedSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_PX,
            16f,
            resources.displayMetrics
        )
//        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, selectedSize);
        textView.setTextColor(resources!!.getColor(client.comm.commlib.R.color.txt_color))
        tvDesc.setTextColor(resources!!.getColor(R.color.hint_color))
        vIndicator.visibility = View.INVISIBLE
    }

    fun goSearch() {
        startActivity(Intent(requireContext(), SearchActivity::class.java))
    }


}